package teaching.controller.baseInfoManage.majorBaseInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import teaching.entity.Major;
import teaching.service.baseInfoManage.common.ExcelUtil;
import teaching.service.baseInfoManage.common.ExcelUtil.ExcelReader;
import teaching.service.baseInfoManage.majorBaseInfo.MajorBaseInfoService;

@Controller
@RequestMapping(value="majorBaseInfo")
public class MajorBaseInfoController {
	
	 /**
	 * 专业信息service
	 */
	 @Autowired
     private MajorBaseInfoService majorBaseInfoService;
	 
	 /**
	  * 添加专业信息
	  * @author GuoFei
	  * @param response
	  * @param request
	  * @return
	 * @throws ParseException 
	  */
	 @RequestMapping(value="addMajor")
	 @ResponseBody
	 public Map<String,Object> addMajor(HttpServletResponse response,HttpServletRequest request) throws ParseException{
		
		 Map<String,Object> map = new HashMap<String, Object>();
		 Major major = new Major();		 
		 major.setMajorId(request.getParameter("majorId"));
		 major.setCollegeId(request.getParameter("collegeId"));
		 major.setMajorName(request.getParameter("majorName"));
		 major.setMajorShortName(request.getParameter("majorShortName"));
		 major.setMajorSort(request.getParameter("majorSort"));
		 major.setMajorManager(request.getParameter("majorManager"));
		 major.setTeachingDirector(request.getParameter("teachingDirector"));
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 major.setCreateTime(sdf.parse(sdf.format(new Date())));
		 List<Major> list = new ArrayList<Major>();
		 list.add(major);
		   try {
			     int status = majorBaseInfoService.addMajor(list);
			     if(status == 1){
			    	 map.put("message", "添加专业成功！");
			     }else{
			    	 map.put("message", "添加专业失败！");
			     }
			     
		   } catch (SQLException e) {
			     // TODO Auto-generated catch block
			      e.printStackTrace();
		   }
		 
		 return map;
	 }
	 
	 /**
	  * 修改专业信息
	  * @author GuoFei
	  * @param response
	  * @param request
	  * @return
	  */
	 @RequestMapping(value="updateMajor")
	 @ResponseBody
	 public Map<String,Object> updateMajor(HttpServletResponse response,HttpServletRequest request){
		 
		 Map<String,Object> map = new HashMap<String, Object>();
		 Map<String,Object> updateMap = new HashMap<String,Object>();
		 
		 //修改专业原来的id
		 String oldMajorId = request.getParameter("oldMajorId");
		 if(oldMajorId != null && !("").equals(oldMajorId) && !("null").equals(oldMajorId)){
			 updateMap.put("oldMajorId", oldMajorId);
			 updateMap.put("majorId", request.getParameter("majorId"));
			 updateMap.put("collegeId", request.getParameter("collegeId"));
			 updateMap.put("majorName", request.getParameter("majorName"));
			 updateMap.put("majorShortName", request.getParameter("majorShortName"));
			 updateMap.put("majorSort", request.getParameter("majorSort"));
			 updateMap.put("majorManager", request.getParameter("majorManager"));
			 updateMap.put("teachingDirector", request.getParameter("teachingDirector"));
			 try {
					int status = majorBaseInfoService.updateMajor(updateMap);
					if(status == 1){
						map.put("message", "修改成功！");
					}else{
						map.put("message", "修改失败！");
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		 }
		
		 return map;
	 }
	 
	 
	 /**
	  * 分页查询专业信息
	  * @author GuoFei
	  * @param page
	  * @param response
	  * @param request
	  * @return
	  */
	 @RequestMapping(value="getMajor")
	 @ResponseBody
	 public Map<String,Object> getMajor(@RequestParam(value="page",required=false) Integer  page,@RequestParam(value="pageSize",required=false) Integer  pageSize,HttpServletResponse response,HttpServletRequest request){	
		 Map<String,Object> map = new HashMap<String, Object>(); 
		 int start = 0; 
		 if(page!=null&&pageSize!=null){
			 start = (page-1)*pageSize;
		 }
		 
		 String majorId = request.getParameter("majorId");
		 Map<String,Object> map2 = new HashMap<String, Object>();
	     map.put("start",start);
	     map.put("pageSize",pageSize);
	     map.put("majorId", majorId);
	     List<Major> majorList = null;
	     try {
			 majorList = majorBaseInfoService.getMajor(map);
			 int  countNum = majorBaseInfoService.getMajorCountNum();
			 map2.put("majorList", majorList);
			 map2.put("countNum", countNum);
		 } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		 }
	     return map2;
	 }
	 
	 /**
	  * 删除专业 级联删除班级+学生+毕设结果
	  * 条件：专业编号majorId
	  * @author GuoFei
	  * @param response
	  * @param request
	  * @return
	  */
	 @RequestMapping(value="deleteMajor")
	 @ResponseBody
	 public Map<String,Object> deleteMajor(HttpServletResponse response,HttpServletRequest request){
		 Map<String,Object> map = new HashMap<String, Object>();
		 String majorId = request.getParameter("majorId");
		 try {
			int status = majorBaseInfoService.deleteMajor(majorId);
			if(status == 1){
				map.put("message", "删除成功");
			}else{
				map.put("message", "删除失败");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return map;
	 }
	 
	 /**
	  * 导出专业
	  * @param response
	  * @param request
	  * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	  */
	 @RequestMapping(value="exportMajor")
	 @ResponseBody
	 public Map<String,Object> exportMajor(HttpServletRequest request) throws FileNotFoundException, IOException{
		  
		    Map<String,Object> map = new HashMap<String, Object>(); 	    
			String basePath = this.getClass().getResource("/").getPath();
			if(System.getProperty("os.name").toLowerCase().indexOf("linux")>=0){
				basePath = basePath.substring(0, basePath.indexOf("/WEB-INF"));
			}else{
				basePath = basePath.substring(1, basePath.indexOf("/WEB-INF"));
			}
			
			String fileName = "template_major.xls";		
			String templatePath = basePath + "/template/baseInfoManage/" + fileName;
			// 先读取模板 
		    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(templatePath));
		    HSSFWorkbook wb = new HSSFWorkbook(fs);  
		    //在webbook中添加一个sheet,对应Excel文件中的sheet  
		    HSSFSheet sheet = wb.getSheetAt(0);  
		    //在sheet中添加表头第0行 
		    HSSFRow row;
		    HSSFCellStyle cellStyle = ExcelUtil.setCellStyle(wb);
		    //写入实体数据 ,数据从数据库得到，  
		    List<Major> list = null;
		    Map<String,Object> map2 = new HashMap<String, Object>();
		    try {
				list = majorBaseInfoService.getMajor(map2);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    
		    if(list!=null){
		    	for (int i = 0; i < list.size(); i++) {
		    		 row = sheet.createRow( i + 1); 		    				                
		            row.createCell(0).setCellValue(list.get(i).getMajorId()); 
		            row.getCell(0).setCellStyle(cellStyle);
		            row.createCell(1).setCellValue(list.get(i).getMajorName()); 
		            row.getCell(1).setCellStyle(cellStyle);
		            row.createCell(2).setCellValue(list.get(i).getMajorShortName());
		            row.getCell(2).setCellStyle(cellStyle);
		            row.createCell(3).setCellValue(list.get(i).getCollegeId()); 
		            row.getCell(3).setCellStyle(cellStyle);
		            row.createCell(4).setCellValue(list.get(i).getMajorSort()); 
		            row.getCell(4).setCellStyle(cellStyle);
		            row.createCell(5).setCellValue(list.get(i).getTeachingDirector()); 
		            row.getCell(5).setCellStyle(cellStyle);
		            row.createCell(6).setCellValue(list.get(i).getMajorManager()); 
		            row.getCell(6).setCellStyle(cellStyle);
			                  		     	     
			    }  
		    }
		  
		    
	    try{  
	    	String path = "file/export";
	    	String realPath = request.getSession().getServletContext().getRealPath("/"+path);
	    	String pathtrue = realPath + "/"+fileName;
	        FileOutputStream fout = new FileOutputStream(pathtrue);  
	        wb.write(fout);  
	        fout.close();  
	        String uri =  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
	       
	        map.put("message", uri+"/"+"TeachingMIS/"+path+"/"+fileName);
	    }  
	    catch (Exception e){ 
	    
	    	map.put("message", "导出失败！");
	        e.printStackTrace();  
	    }  
		 
		 return map;
	 }
	 
	/**
	 * 导入专业
	 * @param fileName
	 * @return
	 * @throws SQLException 
	 * @throws ParseException 
	 */
	 @RequestMapping(value="importMajor")
	 @ResponseBody
	 public Map<String,Object> importMajor(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws SQLException, ParseException{
		    String fileName = file.getOriginalFilename();
			String saveFileName = UUID.randomUUID().toString().replaceAll("-", "") + "-" + fileName;
			String path = "file/import";
			String realPath = request.getSession().getServletContext().getRealPath("/"+path);
			String pathtrue = realPath + "/"+saveFileName;
			try {
				file.transferTo(new File(pathtrue));
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		 Map<String,Object> map = new HashMap<String, Object>();
		 ExcelUtil excelUtil = new ExcelUtil();
		 InputStream is = null;
		
		 try {
			is = new FileInputStream(pathtrue);
		 } catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		 }
		 ExcelReader excelReader = excelUtil.getExcelReader();
		 List<Map<Integer, String>>  list = excelReader.readExcelContent(is);	
		 List<Major>  list2 = new ArrayList<Major>();
		 if(list!=null){
			 for(int i = 0;i<list.size();i++){	
				 if(list.get(i).get(0) != null&&!"".equals(list.get(i).get(0))){
					 Major major = new Major();
					 major.setMajorId(list.get(i).get(0));
					 major.setMajorName(list.get(i).get(1));
					 major.setMajorShortName(list.get(i).get(2));
					 major.setCollegeId(list.get(i).get(3));
					 major.setMajorSort(list.get(i).get(4));
					 major.setTeachingDirector(list.get(i).get(5));
					 major.setMajorManager(list.get(i).get(6));
					 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					 major.setCreateTime(sdf.parse(sdf.format(new Date())));
					 list2.add(major);					
				 }		 
			 }
		 }	
		 majorBaseInfoService.addMajor(list2); 
		 File file2 = new File(pathtrue);
		 if(file2.exists()){
			 file2.delete();
		 }
	     map.put("message", "导入成功！");
		
		 return map;
	 
	 }
	 
	
}
